package com.my.redis;

import com.my.redis.pojo.KeyValue;
import com.my.utils.CommonUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * Created by 80002023 on 2016/6/15.
 */

@Component
public class RedisManagerImpl implements IRedisManager {


    private final Logger logger = LogManager.getLogger(getClass());

    private RedisTemplate<String, String> redisTemplate;

    @Resource
    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 获取 RedisSerializer
     */
    protected RedisSerializer<String> getRedisSerializer() {
        return redisTemplate.getStringSerializer();
    }

    public boolean save(String prefix, KeyValue record) {
        String key = record.getKey();
        if (CommonUtils.isNotEmpty(prefix)) {
            key = prefix + key;
        }
        String value = record.getValue();
        return exec(key, value, record.getExpires());
    }

    public boolean save(String prefix, List<KeyValue> records) {

        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        for (KeyValue record : records) {
            String key = record.getKey();
            if (CommonUtils.isNotEmpty(prefix)) {
                key = prefix + key;
            }
            ops.set(key, record.getValue(), record.getExpires());
        }

        return true;
    }

    public boolean exec(final String key, final String value, final long expires) {
        logger.info("redis add key:value:expires {}:{}:{}", key, value, expires);
        return redisTemplate.execute(new RedisCallback<Boolean>() {
            public Boolean doInRedis(RedisConnection connection)
                    throws DataAccessException {
                RedisSerializer<String> serializer = getRedisSerializer();
                byte[] serializerKey = serializer.serialize(key);
                byte[] serializerValue = serializer.serialize(value);
                if (expires > 60) {
                    connection.setEx(serializerKey, expires, serializerValue);
                    return true;
                } else {
                    return connection.setNX(serializerKey, serializerValue);
                }
            }
        });
    }

    public void get(String key) {
        //redisTemplate.
        //return null;
    }
}
